package com.example.bbs.controller;

import org.w3c.dom.*;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther: zhangxin
 * @Description:
 */
@WebServlet(name = "DispatcherServlet",
        value = "*.action",
        loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {

    Map<String,Object> maps = new HashMap<>();

    public void init(){
        try {
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = documentBuilder.parse(DispatcherServlet.class.getResourceAsStream("/applicationContext.xml"));
            //获取根节点
            Element root = doc.getDocumentElement();
            //获取所有的bean节点
            NodeList list = root.getElementsByTagName("bean");

            for (int i = 0; i < list.getLength(); i++) {
                //bean节点
                Node node = list.item(i);
                //获取bean节点的class和url属性
                NamedNodeMap attrMap = node.getAttributes();
                Node classNode = attrMap.getNamedItem("class");
                Node urlNode = attrMap.getNamedItem("url");
                //获取属性值
                String className = classNode.getNodeValue();
                String url = urlNode.getNodeValue();
                //反射生成业务处理类
                Object obj = Class.forName(className).newInstance();
                maps.put(url,obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void service(HttpServletRequest req, HttpServletResponse resp){

        //获取请求的路径
        String path = req.getServletPath();
        //截取.前内容
        path = path.substring(0,path.indexOf("."));
        System.out.println(path);
        //映射 mapping
        Object bean = maps.get(path);
        if(bean != null){
            Method method = bean.getClass().getMethods()[0];
            try {
                method.invoke(bean,req,resp);
            } catch (Exception e) {
                try {
                    method.invoke(bean);
                } catch (Exception illegalAccessException) {
                    illegalAccessException.printStackTrace();
                }
                method = bean.getClass().getMethods()[1];
                try {
                    method.invoke(bean,req,resp);
                } catch (Exception illegalAccessException) {
                    illegalAccessException.printStackTrace();
                }
            }
        }

    }
}
